var eventObj = require("../event");
var udpOperation = require("../../net/udpOperation")
var fs = require("fs");
var _ = require("underscore");
var TramStatus = require("../basic/TramStatusDt");
var TramStatusJson = require("../basic/TramStatusJson");
var baseInfoUtil = require("../baseInfo");

function DtRunExecutor(){
    this.segmentStatusArr = [];
    this.terminusStatusArr = [];
    this.routeStatusArr = [];
    this.sectionArr = [];
    this.line = null;
    this.tram = null;
    this.interval = null;
    this.updateInterval = 2;
    //模拟车辆数量
    this.runFlag = false;
    //GPS数据测试用 待删除
    this.gpsDataArr = [];
    this.gpsIndex = 0;
    this.tramNum = 0;
    this.tramStatusArr = [];
    this.passTimeBySec = getSysTimeBySecs();
    this.tramEvents = [];
}

var dtRunExecutor = new DtRunExecutor();

module.exports = dtRunExecutor;

/*获取车辆运行计划事件*/
eventObj.event.on("app_event_tram_simulate",function(data){
     var runPlan = baseInfoUtil.createTramRunPlan(data);
     dtRunExecutor.tramNum += runPlan.length;
     _.each(runPlan,function(element,index){
         var tramCode = index >= 9 ? '1' + (index+1) : '10' + (index+1);
        var firstTerminus = element.path.split("-")[0];
        var secondTerminus = element.path.split("-")[1];
        var direct = null;
        if(parseInt(firstTerminus) < parseInt(secondTerminus)){
            direct = 'up';
        }else{
            direct = 'down';
        }
        var tram = new TramStatus({
                                  runExecutor   :  dtRunExecutor,
                                  initTimeBySec :  baseInfoUtil.getSysTimeBySecs(),
                                  tramCode      :  tramCode,
                                  runPlan       :  element,
                                  direct        :  direct
                                //  crossStationArr : obj.crossStationArr
                             });
         tram.init();
         dtRunExecutor.tramStatusArr.push(tram);

  });
  dtRunExecutor.run();   
  udpOperation.createUdpServer();
});

/*获取车辆运行计划事件*/
eventObj.event.on("app_event_dt_simulate",function(data){
    var planData = eval("(" + fs.readFileSync("./upload/schedulePlan.json", "utf-8")+ ")");
    var resolvedData = handleData(planData[0].services);
     //通过遍历运行计划数据建立车辆对象，并启动车辆
     _.each(resolvedData,function(value, key){
        var tram = new TramStatusJson({
                    runExecutor   :  dtRunExecutor,
                    tramCode : key,
                    runPlan  : value});
        dtRunExecutor.tramStatusArr.push(tram);
        tram.createSectionArrData();
     });
     dtRunExecutor.run();

});

eventObj.event.on("tram_runArgs_reply_event",function(data){
   console.log(data);
   _.forEach(dtRunExecutor.tramStatusArr,function(ele,index){
      if(parseInt(ele.tramCode) === data.tramCode){
        ele.serviceNum = data.serviceNum;
        ele.isGetTramArgs = true;
      }
   })
});


DtRunExecutor.prototype.run = function(){
    var $this = this;
    $this.runFlag = true;
    if($this.interval){
        clearInterval($this.interval);
    }
    var update = function(){
        $this.passTimeBySec += $this.updateInterval;
        _.forEach($this.tramStatusArr,function(ele,index){
        //  if(ele.isGetTramArgs){
            ele.run();
            $this.tramEvents.push(ele.sendStatusEventInfo(ele.serviceNum));
          //}

        });
       
        eventObj.event.emit("tram_status_change_event", $this.tramEvents);
        $this.tramEvents.splice(0,$this.tramEvents.length);
    }
    $this.interval = setInterval(update,$this.updateInterval*1000);
}

 function getSysTimeBySecs(){
    var date = new Date();
    if(date){
        return date.getHours()*3600 + date.getMinutes()*60 + date.getSeconds();
    }
}
DtRunExecutor.prototype.getSeconds =function (time){
    if(time){
        var hour = parseInt(time.split(':')[0]);
        var tempMins = time.split(':')[1];
        if(tempMins.charAt(0)==='0'){
            mins = parseInt(tempMins.charAt(1));
        }else{
            mins = parseInt(tempMins);
        }
        return hour*60*60 + mins*60;
    }
}

//将导入的json数据按车辆编号分组打包
function handleData(data){

   var resolvedData = {};
   var tramCodeArr = [];
   _.each(data, function(element,index,list){

      if(_.indexOf(tramCodeArr,element.tramCode)== -1){
          tramCodeArr.push(element.tramCode);
      }
   });
   _.each(tramCodeArr,function(element,index){
      var tempArr = [];
      _.each(data,function(ele,i){
     if(ele.tramCode === element){        
          tempArr.push(ele);
        }
     });
     resolvedData[element] = tempArr;
   });
   return resolvedData;
}



